package edu.guet.server.service;

import edu.guet.server.mapper.PaperMapper;
import edu.guet.server.mapper.UnitTestMapper;
import edu.guet.server.model.Question;
import edu.guet.server.model.dto.AnswerDTO;
import edu.guet.server.model.dto.Survey;
import edu.guet.server.utils.SortABC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class PaperService {
    @Autowired
    PaperMapper paperMapper;
    @Autowired
    private UnitTestMapper unitTestMapper;

    public Survey selectPaper(Integer paperId) {
        return paperMapper.selectPaper(paperId);
    }

    public List<Question> selectQSelectList(Integer paperId) {
        return paperMapper.selectQSelectList(paperId);
    }

    public Integer getQsCount(Integer testId) {
        return paperMapper.getQsCount(testId);
    }

    public Integer getPaperId(Integer testId) {
        return paperMapper.getPaperId(testId);
    }

    public void updatePerMaxScore(Integer paperId, Double qsScore) {
        paperMapper.updatePerMaxScore(paperId, qsScore);
    }


    public Double getresScore(AnswerDTO answerDTO) {
        Integer testId = answerDTO.getTest_id();
        Integer userId = answerDTO.getUser_id();
        //拿到最大分数
        Double maxSocre = paperMapper.getMaxScorePer(answerDTO.getPaper_id());
        //拿到答案列表
        List<AnswerDTO.Ans> ansList = answerDTO.getAnswers();
        Double resScore = 0.0;
        for (AnswerDTO.Ans ans : ansList) {
            ans.setQs_ans(SortABC.sortabc(ans.getQs_ans()));
            String RIGHT = paperMapper.getQuesRight(ans.getQs_id());
            if (ans.getQs_ans().equals(RIGHT)) resScore += maxSocre;
        }
        Integer uId = unitTestMapper.findStuTest(userId, testId);
        if (uId == null) unitTestMapper.addTestScore(resScore, testId, userId);
        else unitTestMapper.updateStuTestScore(resScore, testId, userId);
        return resScore;
    }
}
